package com.kiwi.util.EncryptSet.Impl;

import com.kiwi.util.EncryptSet.Constant.AES;
import com.kiwi.util.EncryptSet.Dto.DeviceInfo;
import com.kiwi.util.EncryptSet.Dto.IdKeyInfoDto;
import com.kiwi.util.EncryptSet.Dto.SessionInfoDto;
import com.kiwi.util.EncryptSet.Interface.SignatureService;
import com.netease.common.util.AESUtil;
import com.netease.common.util.MD5Util;
import com.netease.lottery.base.util.NStringUtil;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

public class SignatureServiceImpl implements SignatureService
{
	protected static final Log log = LogFactory.getLog(SignatureServiceImpl.class);
	public static final String ENCODE = "UTF-8";
	private static final String CONTENT_SPLIT = "&#";
	public static final String DEFAULT_WAP_MARK_NO = "S9PjlWIDD1KEgU71";
	public static final String DEFAULT_WAP_MARK_NO2 = "uc_wap_session";

//	@Autowired
//	DeviceInfoService deviceInfoService;

	@Override
	public String getAppInitKeyById(String id, String deviceId)
	{
		if (!NStringUtil.checkParams(id, deviceId))
			return null;

		String[] content = getContentFromId(id);
		if (!NStringUtil.checkParams(content) || !deviceId.equals(content[1]))
		{
			log.warn("解析id出错,id:" + id + ",deviceId:" + deviceId);
			return null;
		}
		return MD5Util.get(content[0], ENCODE);
	}

	@Override
	public String decryptParams(String params, String key)
	{
		try
		{
			byte[] buffer = AES.decrypt(AES.hex2byte(params), AES.hex2byte(key));
			return new String(buffer, "utf-8");
		}
		catch (Exception e)
		{
			log.warn("解密params出错,params:" + params + ",key:" + key);
			return null;
		}
	}
	/**
	 *
	 * @param id
	 * @return 0 key 1 product
	 */
	private static String[] getContentFromId(String id)
	{
		try
		{
			byte[] buffer = AES.decrypt(AES.hex2byte(id), AES.hex2byte(getPrivateKey()));
			String result = new String(buffer, "utf-8");
			String[] segs = result.split(CONTENT_SPLIT);
			if (segs.length == 3)
				return segs;
		}
		catch (Exception e)
		{
			log.error("解析id异常,id:" + id, e);
		}
		return new String[]
				{ "", "", "" };
	}

	/**
	 * 获取密钥
	 *
	 * @return
	 */
	private static String getPrivateKey()
	{
		String default_key = "54EFA92D090ABCAF44B071D1E3C31F39";// 默认配置

		// 获取密钥
		String pri_key = "";//IPChecker.getSingleValueByKey("mobile-app-key");XXX
		if (StringUtils.isBlank(pri_key))
		{
			pri_key = default_key;
		}
		return pri_key;
	}

	private String getWapPrivateKey()
	{
		String default_key = "O5KGZP0D4MN8JH1V";// 默认配置
		// 获取密钥
		String pri_key = "";//IPChecker.getSingleValueByKey("mobile-wap-key");XXX
		if (StringUtils.isBlank(pri_key))
		{
			pri_key = default_key;
		}
		return pri_key;
	}

	@Override
	public IdKeyInfoDto generateIdAndKeyInfo(String platform, String pdtVersion, String mac, String systemName,
											 String systemVersion, String resolution, String uniqueID, String deviceType, String deviceId)
	{
		IdKeyInfoDto idKeyInfo = new IdKeyInfoDto();
		//之后可以考虑为异步处理
		DeviceInfo deviceInfo = new DeviceInfo();
		deviceInfo.setPlatform(platform);
		deviceInfo.setPdtVersion(pdtVersion);
		deviceInfo.setMac(mac);
		deviceInfo.setSystemName(systemName);
		deviceInfo.setSystemVersion(systemVersion);
		deviceInfo.setResolution(resolution);
		deviceInfo.setUniqueId(uniqueID);
		deviceInfo.setDeviceType(deviceType);
		deviceInfo.setDeviceId(deviceId);
//		DeviceInfo dbInfo = deviceInfoService.get(deviceId);
//		if (null == dbInfo)
//		{
//			deviceInfo.setCreateTime(new Date());
//			deviceInfoService.add(deviceInfo);
//		}
//		else
//		{
//			deviceInfo.setUpdateTime(new Date());
//			deviceInfoService.update(deviceInfo);
//		}

		String keySource = "" + System.nanoTime() + new Random().nextInt();
		String src = keySource + CONTENT_SPLIT + deviceId + CONTENT_SPLIT + platform;

		String id = null;
		try
		{
			id = AES.byte2hex(AES.encrypt(src.getBytes("utf-8"), AES.hex2byte(getPrivateKey())));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		String key = MD5Util.get(keySource, ENCODE);
		idKeyInfo.setId(id);
		idKeyInfo.setKey(key);
		return idKeyInfo;
	}

	@Override
	public String encryptAccountIdSessionId(String accountId, String sessionId, String key)
	{
		try
		{
			String params = "accountId=" + accountId + "&sessionId=" + sessionId;
			return AES.byte2hex(AES.encrypt(params.getBytes("utf-8"), AES.hex2byte(key)));
		}
		catch (Exception e)
		{
			log.error("encryptAccountIdSessionId exception,accountId:" + accountId + ",sessionId:" + sessionId, e);
		}
		return null;
	}

	@Override
	public String encryptWapSession(String accountId, String sessionId)
	{
		try
		{
			/***
			 * 生成加密
			 */
			String keySource = "" + System.nanoTime() + new Random().nextInt();
			String src = keySource + CONTENT_SPLIT + DEFAULT_WAP_MARK_NO + CONTENT_SPLIT
					+ DEFAULT_WAP_MARK_NO2;
			String id = AES.encrypt(src.toString(), getWapPrivateKey());
			String key = MD5Util.get(keySource, ENCODE);
			String encodeSession = AES.encrypt(accountId + "|" + sessionId, key);
			return id + "|" + encodeSession;
		}
		catch (Exception e)
		{
			log.error("wap encrypt 加密session异常,accountId:" + accountId + ",sessionId:" + sessionId, e);
		}
		return null;
	}

	@Override
	public SessionInfoDto decryptWapSession(String uc_sess)
	{

		try
		{
			if (uc_sess.indexOf("\\|") <= 0)
				log.error("参数不合法uc_sess" + uc_sess + "参数格式不正确，id|sess");
			String params[] = uc_sess.split("\\|");
			if (ArrayUtils.isEmpty(params) || params.length != 2)
				log.error("参数不合法" + "uc_sess:" + uc_sess +
						"格式不正确：id|sess");
			String keySource[] = AESUtil.decrypt(params[0], getWapPrivateKey()).split(CONTENT_SPLIT);

			if (keySource.length != 3 || !keySource[1].equals(DEFAULT_WAP_MARK_NO) || !keySource[2]
					.equals(DEFAULT_WAP_MARK_NO2))
				log.error("状态不合法" + "id" + uc_sess +"id|markNo1|markNo2");
			/***
			 * 对应数据不正确
			 */
			if (!DEFAULT_WAP_MARK_NO.equals(keySource[1]) || !DEFAULT_WAP_MARK_NO2
					.equals(keySource[2]))
				log.error("状态不合法" + "markNo1或markNo2" + uc_sess +
						"id|markNo1|markNo2");
			String key = MD5Util.get(keySource[0], ENCODE);
			/****
			 * 根据算出的key解密session
			 */
			String sess = AESUtil.decrypt(params[1], key);
			if (sess.indexOf("\\|") <= 0)
				log.error("参数不合法" + "accountId|sessionId" + uc_sess +
						"格式不正确：accountId|sessionId");
			String sessionCookies[] = sess.split("\\|");
			if (ArrayUtils.isEmpty(sessionCookies) || sessionCookies.length != 2)
				log.error("参数不合法" + "accountId|sessionId" + uc_sess +
						"格式不正确：accountId|sessionId");
			SessionInfoDto sessionInfoDto = new SessionInfoDto(sessionCookies[0], sessionCookies[1]);
			return sessionInfoDto;
		}
		catch (Exception e)
		{
			log.error("解密session报错异常，请检查uc_sess=" + uc_sess, e);
		}
		return null;
	}
	

	
	public String encodeStr(String params) throws UnsupportedEncodingException, Exception
	{
		String deviceId = "528C4C26-9C09-49D1-B7D8-4260DB3754DB";
		String id = "97619702FD39FC400822F1FAC64F854E01ED1325EC0C8F191EA754D8C9CA018F093454955C51F4B07354AC2060E463B2D437A949D13C6E7FBB7A270C3077E5FCE0485F218D309B1E49CBFF426B1125AC";
			
		String key = getAppInitKeyById(id, deviceId);
			
		return  AES.byte2hex(AES.encrypt(params.getBytes("utf-8"), AES.hex2byte(key)));

	}
	
	public String decodeStr(String deviceId, String id, String Params) throws UnsupportedEncodingException, Exception
	{
		
		String key = getAppInitKeyById(id, deviceId);
		
		return "解密结果" + decryptParams(Params, key);
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException, Exception
	{

//		SignatureServiceImpl signatureService = new SignatureServiceImpl();
//		log.info(signatureService.encodeStr("mobile=13501104287&password=123456a&verifyCode=123456"));
//
//		String id = "B8247CBA3604A4564DE31CBF1CB6AEF0A450FD31DC862AB03A11FE47F609D9BB6D46BA2D2E3872D4BD841C101E28B141C80BAE7E019B8E6422EDE1326DD26CE7";
//		String deviceId = "865729038215966";
//		String Params = "6262EA98CAF0FF15F6F1FF0F03366C3B9B7C67A75ADA0206E85CD04F58462DD555B5158A8008790BEF5FA9E6541629D54E0E348706E6333C2C8A1004AF16C890";
//
//		log.info(signatureService.decodeStr(deviceId, id, Params));

		//wss://game.hiwan360.com/mario/pandora-websocket,Mario,90000000189000000019,9000000019,B77ED136A6D92D53B78C2D7D97D6EB709852DC78A4184B600E0F5E0F33F15CB6FD5E2D9B1F5B8D02E82A273523899ECA9C1B956A9ABECAE1CD649AD2E8E23896|8B891639C81BB745E52C8D466A71AB260D17E072C560AD7A9486B97C3D4211E6
		SignatureServiceImpl ss = new SignatureServiceImpl();
		String key1 = "ECC2C41E6FE8E4F7E919C545F53203C54BCF69AA227FDFCE1D33CC7D105F0FE7B3D26E100BE3BFF93D18572FB0B875B2C0D7CC5AB7CCC8B02FAAAF4FB851DC9C|46FDF51ED29633F3CE63D8AD7779545CF49EA3642F1CE32967323EA2F8AF1DCE45712068FB575D3C83B9015C8DD3B396";
		String key2 ="511828861";
		ss.decryptParams(key1,key2);
	/*	Long baseid = 9000009000L;
		Long aid = 0L;
		Long aid2 = 0L;
		String session = "helloworld";
		for (int i = 0; i < 1000; i++) {
			aid = baseid + i ;
            Random random = new Random();
			aid2 = aid+1;
			String tk = ss.encryptWapSession(String.valueOf(aid),session);
			String ln = aid+","+tk;
			//String tk2 = ss.encryptWapSession(String.valueOf(aid2),session);
			//String ln = "wss://game.hiwan360.com/mario/pandora-websocket,Mario,"+aid+aid2 + "," + aid+","+tk;
			//String ln2 = "wss://game.hiwan360.com/mario/pandora-websocket,Mario,"+aid+aid2 + "," + aid2+","+tk2;
			System.out.println(ln);
			//System.out.println(ln2);

		}*/
		//ss.encryptWapSession(String.valueOf(aid),session);
		//SessionInfoDto sessionraw = ss.decryptWapSession("f7ae9ebf4af5374bb048a0b8e2624c73");
		//System.out.println(sessionraw.getSessionId());
		//String tk = ss.encryptWapSession(String.valueOf("10001"),"f7ae9ebf4af5374bb048a0b8e2624c73");
		//System.out.print(tk);



	}

}
